<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8 clearfix" style="margin-top: 2px">
      <el-col :span="18">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
        >
          <!-- <el-form-item> -->
          <!-- <el-select v-model="searchData.field" size="small" style="width:150px" clearable placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                        </el-option>
                    </el-select> -->
          <!-- <el-input
                            v-model="searchData.keyword"
                            placeholder="请输入"
                            clearable
                            size="small"
                            style="width: 240px"
                        /> -->
          <!-- </el-form-item> -->
          <el-form-item label="用户姓名" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入用户姓名"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="1.5" style="float: right; margin: 8px 5px 0px 0px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          >添加用户</el-button
        >
      </el-col>
    </el-row>

    <div class="table" style="height: 100%; background: white; padding: 20px">
      <el-table
        v-loading="loading"
        :data="UserList"
        @selection-change="handleSelectionChange"
        :header-cell-style="table_style"
        max-height="650"
      >
        <el-table-column type="selection" width="80" align="center" />
        <el-table-column
          label="序号"
          type="index"
          width="60"
          sortable
          align="center"
        />
        <el-table-column
          label="用户姓名"
          prop="nickName"
          width="100"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="登录名"
          prop="userName"
          width="150"
          align="center"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="所属岗位"
          prop="postName"
          :show-overflow-tooltip="true"
          width="200"
          align="center"
        />
        <el-table-column
          label="所属机构"
          prop="agencyName"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column
          label="联系方式"
          prop="telephone"
          :show-overflow-tooltip="true"
          width="150"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
          width="250"
          class-name="small-padding"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-key"
              @click="handleResetPwd(scope.row)"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row class="clearfix">
        <el-button
          class="delete"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-row>
    </div>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="formbox">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          class="userFrom"
          label-width="80px"
        >
          <el-form-item label="用户Id" prop="userId" v-show="false">
            <el-input v-model="form.userId" />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input
              :disabled="Boolean(form.userId)"
              style="width: 50%"
              v-model="form.userName"
              placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            v-if="Boolean(!form.userId)"
          >
            <el-input
              style="width: 50%"
              v-model="form.password"
              placeholder="设置密码"
              type="password"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="nickName">
            <el-input
              style="width: 50%"
              v-model="form.nickName"
              placeholder="请输入姓名"
            />
          </el-form-item>
          <el-form-item label="联系方式" prop="telephone">
            <el-input
              style="width: 50%"
              v-model="form.phonenumber"
              placeholder=""
            />
          </el-form-item>
          <el-form-item label="联系地址" prop="address" class="address">
            <el-cascader
              size="large"
              :options="addressOptions"
              v-model="form.addressOptions"
            >
                      </el-cascader
            >
            <el-input
              style="width: 46%; margin-left: 13px"
              v-model="form.address"
              placeholder=""
            />
          </el-form-item>
          <el-row>
            <el-col :span="10">
              <el-form-item label="岗位" prop="postId">
                <el-select
                  v-model="form.postId"
                  filterable
                  placeholder="请选择"
                  @change="resetRolePrivIDs($event, 'getRole')"
                >
                  <el-option
                    v-for="item in roleOptions"
                    :key="item.value"
                    :label="item.label"
                    :disabled="
                      item.label == '超级管理员' || item.label == '机构管理员'
                    "
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item label="所属机构" prop="agencyId">
                <el-select
                  v-model="form.agencyId"
                  filterable
                  @change="resetAgencyPrivIDs($event, 'getAgency')"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in agencyOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="菜单权限" prop="permissions">
            <el-checkbox
              v-model="menuExpand"
              @change="handleCheckedTreeExpand($event, 'menu')"
              >展开/折叠</el-checkbox
            >
            <el-checkbox
              v-model="menuNodeAll"
              :disabled="true"
              @change="handleCheckedTreeNodeAll($event, 'menu')"
              >全选/全不选</el-checkbox
            >
            <el-checkbox
              v-model="form.menuCheckStrictly"
              :disabled="true"
              @change="handleCheckedTreeConnect($event, 'menu')"
              >联动选择</el-checkbox
            >
            <el-tree
              :disabled="true"
              class="tree-border"
              :data="menuOptions"
              show-checkbox
              ref="menu"
              node-key="menuId"
              :check-strictly="!form.menuCheckStrictly"
              empty-text="加载中，请稍后"
              :props="defaultProps"
            ></el-tree>
          </el-form-item>

          <!-- <el-form-item label="上传">
                    <el-upload ref="upload" :file-list="form.lawfile" 
                    :on-success="handleChange"
                    :action="field102Action" 
                    :on-preview="handlePreview"
                    :before-remove="beforeRemove"
                    :on-remove="handleRemove" 
                     >
                        <el-button slot="trigger" size="small" type="primary" >上传文件</el-button>
                    </el-upload>
                </el-form-item> -->
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  delFile,
  resetUserPwd,
} from "@/api/system/user";
import { listRoleAll, getRoleMenu } from "@/api/system/role";
import { listAgencyAll, getAgencyMenu } from "@/api/system/agency";
import { saveAs } from "file-saver";
import { encryptes } from "@/utils/jsencrypt";
export default {
  name: "User",
  data() {
    return {
      //上传文件地址
      field102Action: "/dev-api/File",
      //变更机构、岗位、权限
      permissionsID: 1009,
      //搜索下拉
      options: [
        {
          value: "nickName",
          label: "用户姓名",
        },
        {
          value: "agencyName",
          label: "所属机构",
        },
        {
          value: "postName",
          label: "所属岗位",
        },
        {
          value: "phonenumber",
          label: "联系方式",
        },
      ],
      //地址选择
      addressOptions: this.regionData,
      // selectedOptions: [],
      //岗位下拉
      roleOptions: [],
      // 机构下拉
      agencyOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 角色表格数据
      UserList: [],
      // 显示搜索条件
      showSearch: true,
      loading: false,
      // 查询条件
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
      },
      // searchData:{
      //     //查询字段
      //     field: "nickName",
      //     //查询关键字
      //     keyword:undefined,
      // },
      // 总条数
      total: 0,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      // 权限菜单列表
      menuOptions: {},
      //role自带权限
      rolePrivIDs: [],
      //agency自带权限
      agencyPrivIDs: [],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        agencyId: [
          { required: true, message: "所属机构不能为空", trigger: "blur" },
        ],
        postId: [
          { required: true, message: "所属岗位不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],

        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      table_style: { background: "#DADDE9", color: "#000", height: "44px" },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.menuOptions = this.restTree();
  },
  methods: {
    // 类型选择
    typeFormat(row, column) {
      return row.agencyType ? "组织" : "个体";
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      // console.log(this.queryParams);
      listUser(this.queryParams).then((response) => {
        this.UserList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item["userId"]);
      this.multiple = !selection.length;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // if(this.searchData.keyword){this.queryParams[this.searchData.field]=this.searchData.keyword}
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.searchData = {
        //查询字段
        field: "nickName",
        //查询关键字
        keyword: undefined,
      };
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (
        !this.$store.getters.permissions.includes("*:*:*") &&
        !this.$store.getters.permissions.includes("system:user:delete")
      ) {
        this.Message({
          message: "无权限!",
          type: "error",
        });
        return;
      }
      let UserIds = undefined;
      if (row.userId == null) {
        UserIds = this.ids;
      } else {
        UserIds = [row.userId];
      }
      this.$confirm(`是否确认删除此 ${UserIds.length} 条用户数据项?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delUser(UserIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        //role自带权限
        (this.rolePrivIDs = []),
        //agency自带权限
        (this.agencyPrivIDs = []),
        (this.form = {
          userId: undefined, //用户id
          userName: undefined, //用户名
          nickName: undefined, //用户名字
          addressOptions: [], //地区
          address: undefined, //详细地址
          phonenumber: undefined, //联系电话
          postId: undefined, //所属岗位
          postName: undefined,
          agencyId: undefined, //所属机构
          agencyName: undefined,
          password: undefined,
          permissions: [], //权限列表
          lawfile: [],
          menuCheckStrictly: false, //权限菜单联动
        });
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (
        !this.$store.getters.permissions.includes("*:*:*") &&
        !this.$store.getters.permissions.includes("system:user:add")
      ) {
        this.Message({
          message: "无权限!",
          type: "error",
        });
        return;
      }
      this.getOptionsData();
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (
        !this.$store.getters.permissions.includes("*:*:*") &&
        !this.$store.getters.permissions.includes("system:user:update")
      ) {
        this.Message({
          message: "无权限!",
          type: "error",
        });
        return;
      }
      this.getOptionsData();
      this.reset();
      const UserId = row.userId || this.ids;
      getUser(UserId).then((response) => {
        // console.log(response.data)
        this.form = response.data.user;
        this.form.agencyName = response.data.agency.agencyName;
        this.form.agencyId = response.data.agency.agencyId;
        this.resetAgencyPrivIDs(this.form.agencyId);
        this.form.postName = response.data.post.postName;
        this.form.postId = response.data.post.postId;
        this.resetRolePrivIDs(this.form.postId);
        this.form.permissions = response.data.permissions;
        let checkedKeys = response.data.permissions;
        this.open = true;
        checkedKeys.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          });
        });
        this.title = "修改用户信息";
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.form.deptCheckStrictly = value ? true : false;
      }
    },
    created() {
      this.getList();
    },
    // 所有权限菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        // this.$refs.upload.submit();

        if (valid) {
          if (this.form.userId != undefined) {
            this.form.permissions = this.getMenuAllCheckedKeys();
            // this.form.password = "";
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.permissions = this.getMenuAllCheckedKeys();
            this.form.password = encryptes(this.form.password);
            addUser(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //地址联动
    addressChange(arr) {},
    //岗位权限联动，权限取交集
    resetRolePrivIDs(value) {
      const valueObj = this.roleOptions.find((item) => {
        return item.value === value;
      });
      if (valueObj != undefined) {
        this.form.postName = valueObj.label;
      }
      getRoleMenu(value).then((response) => {
        this.rolePrivIDs = response.data.permissions;
        this.form.permissions.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, false, false);
          });
        }); //把所有的取消勾选
        this.form.permissions = this.rolePrivIDs.filter((val) => {
          return this.agencyPrivIDs.indexOf(val) > -1;
        });
        this.form.permissions.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          });
        });
      });
    },
    //机构权限联动,权限取交集
    resetAgencyPrivIDs(value) {
      const valueObj = this.agencyOptions.find((item) => {
        return item.value === value;
      });
      if (valueObj != undefined) {
        this.form.agencyName = valueObj.label;
      }
      // console.log(value);
      getAgencyMenu(value).then((response) => {
        this.agencyPrivIDs = response.data.permissions;
        this.form.permissions.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, false, false);
          });
        }); //把所有的取消勾选
        this.form.permissions = this.agencyPrivIDs.filter((val) => {
          return this.rolePrivIDs.indexOf(val) > -1;
        });
        this.form.permissions.forEach((v) => {
          this.$nextTick(() => {
            this.$refs.menu.setChecked(v, true, false);
          });
        });
      });
    },
    //获取机构列表和岗位列表，并转为options数据
    getOptionsData() {
      listRoleAll().then((response) => {
        this.roleOptions = this.resetOptions(
          response.data,
          "postId",
          "postName"
        );
      });
      listAgencyAll().then((response) => {
        this.agencyOptions = this.resetOptions(
          response.data,
          "agencyId",
          "agencyName"
        );
      });
    },
    //部分权限控制
    setDisabled() {
      return this.$store.getters.permissions.includes(this.permissionsID);
    },
    //删除文件
    beforeRemove(file, fileList) {
      //    if(!this.$store.getters.permissions.includes(this.permissionsID)){
      //         this.Message({
      //             message:"无权限!",
      //             type:'error'
      //         })
      //         return false;
      //     }
      // return this.$confirm(`确定移除 ${ file.name }？`);
      return this.$confirm(`是否确认删除此文件?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    },
    //删除文件
    handleRemove(file, fileList) {
      this.form.lawfile.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.form.lawfile.splice(index, 1);
        }
      });
      delFile(file);
    },
    //下载文件
    handlePreview(file) {
      if (!this.$store.getters.permissions.includes(this.permissionsID)) {
        this.Message({
          message: "无权限!",
          type: "error",
        });
        return;
      }
      saveAs(file.url, file.name);
    },
    //文件列表改变
    handleChange(response, file, fileList) {
      response.data && this.form.lawfile.push(response.data[0]);
    },
    //重构权限树
    restTree() {
      const val = JSON.parse(JSON.stringify(this.$store.getters.menuOptions));
      const R = (f, s) => {
        s.map(
          (i) => (
            f(i),
            i.children && i.children != undefined ? R(f, i.children) : 0,
            i
          )
        );
        return s;
      };
      const data = R((i) => {
        if (i._disabled === undefined) {
          i._disabled = i.disabled === undefined ? false : i.disabled;
        }
        i.disabled = true;
      }, val);
      return data;
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      if (
        !this.$store.getters.permissions.includes("*:*:*") &&
        !this.$store.getters.permissions.includes("system:user:reset")
      ) {
        this.Message({
          message: "无权限!",
          type: "error",
        });
        return;
      }
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          const pwd = encryptes(JSON.parse(JSON.stringify(value)));
          resetUserPwd(row.userId, pwd).then((response) => {
            this.msgSuccess("修改成功，新密码是：" + value);
            if (this.$store.getters.userData.userId == row.userId) {
              setTimeout(() => {
                this.MessageBox.confirm(
                  "登录状态已过期，您可以继续留在该页面，或者重新登录",
                  "系统提示",
                  {
                    confirmButtonText: "重新登录",
                    type: "warning",
                  }
                )
                  .then(() => {
                    this.$store.dispatch("LogOut").then(() => {
                      location.href = "/index";
                    });
                  })
                  .catch(() => {
                    this.$store.dispatch("LogOut").then(() => {
                      location.href = "/index";
                    });
                  });
              }, 2000);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped>
/* .userFrom{ padding: 0px 30px;} */
.description {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: ""; /*不用有内容也可以*/
}

.clearfix:after {
  clear: both;
}

.clearfix {
  *zoom: 1;
}
.delete {
  margin-top: 25px;
  margin-left: 1px;
}
.agencyInfo {
  padding: 0px 40px;
}
.agencyUserInfo {
  padding: 0px 40px;
}
.el-form-item {
  margin-bottom: 18px;
}
.formbox {
  padding: 0px 20px;
}
/* .address{
    display: flex;
    justify-content: space-between;
} */
</style>

